<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\api\model\ProjectClass as ProjectClassModel;
use app\api\model\ProjectWeeks as ProjectWeeksModel;
use app\api\model\ProjectInfo as ProjectInfoModel;
use think\Request;

class Statistics extends Base
{
    /**
     * 周报总览
     * @param Request $request
     * @return \think\response\Json
     */
    public function weeksdisplay(Request $request)
    {
        try {

            $CurrTime = time();
            $date = $request->param('date');
            if(isset($date)){
                $dateRe = isDateValid($date);
                if(!$dateRe){
                    $tr = ['status'=>false,'msg'=>'时间格式不合法'];
                    return $tr;
                }
                $CurrWeek = date('W',strtotime($date));
                $CurrTime = strtotime($date);
                $CurrMonth = strtotime(date('Y-m',strtotime($date)));
            }else{
                $CurrWeek = date('W');
                $CurrMonth = strtotime(date('Y-m'));
            }
            $ProjectWeeksModel = new ProjectWeeksModel();
            //$ProjectInfoModel = new ProjectInfoModel();
            $ProjectClassModel = new ProjectClassModel();
            //$classlist = $ProjectClassModel->where('status','=','1')->select();

            $buildinglist = $ProjectWeeksModel->alias('w')
                ->field('w.week,w.id,w.uid,w.project_id,w.class_id,w.stage_id,w.main_content,w.update_time,
                    w.create_time,pro.iskey,
                    pro.project_no,pro.project_name,u.realname as project_pm,m.main_content as curr_moth_plan,w.project_desc,
                    (SELECT GROUP_CONCAT(content) FROM (select concat(content,"（",percentage,"%）\n ") as content,weeks_id FROM zt_project_weeks_workcontent ) t where weeks_id = w.id) as content,
                    (SELECT GROUP_CONCAT(next_content) FROM (select concat(next_content,"（",next_percentage,"%）\n ") as next_content,weeks_id FROM zt_project_weeks_workplan ) tt where weeks_id = w.id) as next_content'
                )
                ->leftjoin('project_info pro','w.project_id = pro.id')
                ->leftjoin('user u','pro.project_pm = u.id')
                ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                ->where('pro.p_e_time','>',$CurrTime)
                ->where("w.week",'=',$CurrWeek)
                ->order('pro.iskey desc')
                ->select();


//            $buildingtotalNumlist =  $ProjectClassModel->alias('c')
//                                                       ->field('c.name,count(c.name) as num')
//                                                       ->leftjoin('project_info p','c.id = p.project_class')
//                                                       ->where('p_e_time','>',$CurrTime)
//                                                       ->group('c.name')
//                                                       ->select();


            $buildingtotalNumlist = $ProjectClassModel->alias('c')
                                                    ->field('c.name,count(c.name) as num')
                                                    ->leftjoin('project_weeks w','c.id = w.class_id')
                                                    ->leftjoin('project_info pro','w.project_id = pro.id')
                                                    ->leftjoin('user u','pro.project_pm = u.id')
                                                    ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                                                    ->where('pro.p_e_time','>',$CurrTime)
                                                    ->where("w.week",'=',$CurrWeek)
                                                    ->order('pro.iskey desc')
                                                    ->group('c.name')
                                                    ->select();

            $buildingtotalNum = $ProjectClassModel->alias('c')
                                                    ->field('c.name,count(c.name) as num')
                                                    ->leftjoin('project_weeks w','c.id = w.class_id')
                                                    ->leftjoin('project_info pro','w.project_id = pro.id')
                                                    ->leftjoin('user u','pro.project_pm = u.id')
                                                    ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                                                    ->where('pro.p_e_time','>',$CurrTime)
                                                    ->where("w.week",'=',$CurrWeek)
                                                    ->order('pro.iskey desc')
                                                    ->count();


            $buildedlist = $ProjectWeeksModel->alias('w')
                ->field('w.week,w.id,w.uid,w.project_id,w.class_id,w.stage_id,w.main_content,pro.iskey ,w.update_time,w.create_time,
                    pro.project_no,pro.project_name,u.realname as project_pm,m.main_content as curr_moth_plan,w.project_desc,
                    (SELECT GROUP_CONCAT(content) FROM (select concat(content,"（",percentage,"%）\n ") as content,weeks_id FROM zt_project_weeks_workcontent ) t where weeks_id = w.id) as content,
                    (SELECT GROUP_CONCAT(next_content) FROM (select concat(next_content,"（",next_percentage,"%）\n ") as next_content,weeks_id FROM zt_project_weeks_workplan ) tt where weeks_id = w.id) as next_content'
                )
                ->leftjoin('project_info pro','w.project_id = pro.id')
                ->leftjoin('user u','pro.project_pm = u.id')
                ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                ->where('pro.p_e_time','<',$CurrTime)
                ->where("w.week",'=',$CurrWeek)
                //->where("pro.iskey",'=','1')
                ->order('pro.iskey desc')
                ->select();

            $buildedtotalNumlist =   $ProjectClassModel->alias('c')
                                                        ->field('c.name,count(c.name) as num')
                                                        ->leftjoin('project_weeks w','c.id = w.class_id')
                                                        ->leftjoin('project_info pro','w.project_id = pro.id')
                                                        ->leftjoin('user u','pro.project_pm = u.id')
                                                        ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                                                        ->where('pro.p_e_time','<',$CurrTime)
                                                        ->where("w.week",'=',$CurrWeek)
                                                        //->where('pro.iskey','=','1')
                                                        ->order('pro.iskey desc')
                                                        ->group('c.name')
                                                        ->select();


            $buildedtotalNum = $ProjectClassModel->alias('c')
                                                    ->field('c.name,count(c.name) as num')
                                                    ->leftjoin('project_weeks w','c.id = w.class_id')
                                                    ->leftjoin('project_info pro','w.project_id = pro.id')
                                                    ->leftjoin('user u','pro.project_pm = u.id')
                                                    ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                                                    ->where('pro.p_e_time','<',$CurrTime)
                                                    ->where("w.week",'=',$CurrWeek)
                                                    ->order('pro.iskey desc')
                                                    ->count();

            $result = [
                           "status"=>true,
                           "msg"=>"获取成功！",
                           "data"=>[
                               "building"=>["weeklist"=>$buildinglist,"projectTotal"=>$buildingtotalNum,"list"=>$buildingtotalNumlist],
                               "builded"=>["weeklist"=>$buildedlist,"projectTotal"=>$buildedtotalNum,"list"=>$buildedtotalNumlist]
                           ]
                       ];
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function allprojectlist(Request $request){
        try {

            $CurrTime = time();
            $ProjectInfoModel = new ProjectInfoModel();
            $uid = $request->param('uid');
            $where = array();
            if($uid){
                $where["p.project_pm"] = $uid;
            }
            $list = $ProjectInfoModel->alias('p')
                ->field('p.id,p.project_name,p.status as p_status,s.name as stageName,r.status,r.start_time as startTime,r.end_time as endTime,r.stage_id')
                ->join('project_info_stage_route r','p.id=r.project_id')
                ->join('project_stage s','r.stage_id = s.id')
                ->where($where)
                ->order('r.sort desc,r.id asc')
                ->select();

            //return $ProjectInfoModel->getLastSql();

            $list_tmp = $ProjectInfoModel->alias('p')
                ->DISTINCT(true)
                ->where($where)
                ->field('p.id,p.project_name,p.iskey')
                ->join('project_info_stage_route r','p.id=r.project_id')
                ->join('project_stage s','r.stage_id = s.id')
                ->order('p.iskey desc')
                ->select();


            $t = [];
            foreach($list_tmp as $k=>$vo){
                //status: -1为未开始，0是异常，1是正常，2是变更项目
                //$t[$k]['id'] =$vo['id'];
                $t[$k]['project_name'] =$vo['project_name'];
                $t[$k]['iskey'] =$vo['iskey'];
                foreach ($list as $j=>$v){
                    if(($v['id'] == $vo['id'])){
                        if($CurrTime < $v['startTime']) $v['status'] = -2;
                        $tmp['stage'] = 0;
                        if($CurrTime > $v['startTime'] && $CurrTime < $v['endTime']) {
                            $tmp['stage'] = 1;
                        }
                        $tmp['stageName'] = $v['stageName'];
                        if($v['p_status'] == 1){
                            $tmp['status'] = $v['status'];
                        }else{
                            $tmp['status'] = $v['p_status'];
                        }
                        $tmp['startTime'] = date("Y-m-d",$v['startTime']);
                        $tmp['endTime'] = date("Y-m-d",$v['endTime']);
                        $tmp['passStatus'] = 0;
                        $tmp['project_id'] = $v['id'];
                        $tmp['stage_id'] = $v['stage_id'];
                        $t[$k]['datas'][]= $tmp;
                    }
                }

            }


            if($list) $resutl = ["status"=>true,"data"=>["list"=>$t],"msg"=>"获取列表成功！"];
            else $resutl = ["status"=>false,"data"=>"","msg"=>"获取列表失败！"];
            return json($resutl);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function allprojectTip(Request $request){
        try {
            $uid = $request->param('uid');
            $where =[];
            if($uid){
                $where['project_pm'] = $uid;
            }
            $ProjectInfoModel = new ProjectInfoModel;
            $projectTotal = $ProjectInfoModel->where($where)->count(); //项目总数

            $where['status'] = -1;
            $unnomral = $ProjectInfoModel->where($where)->count(); //异常

            $where = [];
            $where[] = ['status','IN','3,4'];
            if($uid) $where[] = ['project_pm','=',$uid];
            $save = $ProjectInfoModel->where($where)->count(); //维护数

            $where = [];
            $where[] = ['status','=','2'];
            if($uid) $where[] = ['project_pm','=',$uid];
            $stop = $ProjectInfoModel->where($where)->count(); //暂停数

            $where = [];
            $where[] = ['status','=','-2'];
            if($uid) $where[] = ['project_pm','=',$uid];
            $notstart = $ProjectInfoModel->where($where)->count(); //未开始数

            $where = [];
            $where[] = ['status','=','5'];
            if($uid) $where[] = ['project_pm','=',$uid];
            $finished = $ProjectInfoModel->where($where)->count(); //完结数

            $curr_time = time();
            $where =[];
            if($uid){
                $where[] = ['project_pm','=',$uid];
            }
            $where[] = ['p_e_time','>',$curr_time];
            $where[] = ['status','=',1];
            $building = $ProjectInfoModel->where($where)->count(); //在建项目

            $data['projectTotal'] = $projectTotal;
            $data['unnomral'] = $unnomral;
            $data['save'] = $save;
            $data['building'] = $building;
            $data['stop'] = $stop;
            $data['notstart'] = $notstart;
            $data['finished'] = $finished;
            $result = ['status'=>true,'msg'=>'操作成功','data'=>$data];
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }
}
